package com.yuneec.fly.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Created by zd.zhang on 2016/6/22.
 */
public class CommonUtils {

    public static File getCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    public static File getFileDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalFilesDir(null).getPath();
        } else {
            cachePath = context.getFilesDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    public static int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static long getAvailableExternalMemorySize() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
        long megAvailable = bytesAvailable / (1024 * 1024);
        return megAvailable;
    }

    public static boolean isExternalOutofMemory() {
        return getAvailableExternalMemorySize() <= 300;
    }

    public static File getSavedMediaPath() {
        String root = Environment.getExternalStorageDirectory().toString();
        File mediaDir = new File(root + "/flightmode/media_data");
        mediaDir.mkdirs();
        return mediaDir;
    }

    public static void checkMediaCount(final String mediaType, final int limitThreshold) {
        File saveMediaPath = getSavedMediaPath();
        final File[] videoMediaArray = saveMediaPath.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String filename) {
                return filename.contains(mediaType);
            }
        });
        if (limitThreshold > videoMediaArray.length) {
            return;
        }
        Arrays.sort(videoMediaArray, new Comparator<File>() {
            public int compare(File f1, File f2) {
                return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified());
            }
        });
        for (int i = limitThreshold; i < videoMediaArray.length; ++i) {
            if (videoMediaArray[i] != null && videoMediaArray[i].exists()) {
                videoMediaArray[i].delete();
            }
        }
    }

    public static void saveBitmap(final Bitmap bitmap) {
        try {
            File mediaDir = getSavedMediaPath();
            mediaDir.mkdirs();
            File pic = new File(mediaDir, System.currentTimeMillis() + ".png");
            FileOutputStream fos = new FileOutputStream(pic);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            LogUtils.e("保存图片失败:\n\t" + sw.toString());
        }
    }
}
